package com.quasar.hpatient.view.record;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.DailyRecordDetailsData;
import com.quasar.hpatient.onInterface.OndailyRecordListener;
import com.quasar.hpatient.presenter.DailyRecordPresenter;
import com.quasar.hpatient.utils.OutliersValues;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.view.adapter.BloodPressureAdapter;
import com.quasar.hpatient.widget.SeekBarEditWidget;
import com.quasar.hpatient.widget.WidgetDateAdd;
import com.quasar.hpatient.widget.WidgetTime;
import com.quasar.hpatient.widget.lineChartView;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 血压记录
 */
@OptionsMenu(R.menu.menu_preservation)
@EActivity(R.layout.activity_blood_pressure)
public class BloodPressureActivity extends BaseActivity implements OndailyRecordListener {

    private BloodPressureAdapter bloodPressureAdapter;
    private DailyRecordPresenter dailyRecordPresenter;

    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.lc_post_list)
    lineChartView lc_post_list;
    @ViewById(R.id.wd_dataAdd)
    WidgetDateAdd wd_dataAdd;
    //血压高
    @ViewById(R.id.sw_blood_high)
    SeekBarEditWidget sw_blood_high;
    //血压低
    @ViewById(R.id.sw_blood_low)
    SeekBarEditWidget sw_blood_low;
    //时分
    @ViewById(R.id.wt_time)
    WidgetTime wt_time;
    @Extra
    String TimeVal;//其他跳转过来的时间

    @AfterViews
    void init() {
        initView();
        initData();
        initToolbar();
    }

    @Override
    protected void initView() {
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);
        //隐藏日期按钮
        wd_dataAdd.hideViewDate();
        if (TimeVal != null && TimeVal.length() > 0) {
            wd_dataAdd.setTimeDate(TimeVal);
        }

        //手动输入检测值
        sw_blood_high.onClickTextView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittText(null);
            }
        });
        sw_blood_low.onClickTextView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittText(null);
            }
        });
    }

    @Override
    protected void initData() {
        dailyRecordPresenter = new DailyRecordPresenter(this);
        OneDayDailyRecord();
    }


    //初始化adapter布局
    public void initAdapter(List<TemperatureTableItem> data) {

        bloodPressureAdapter = new BloodPressureAdapter(data);
        rv_list.setAdapter(bloodPressureAdapter);

        bloodPressureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                    case R.id.tv_val_low:
                        if (bloodPressureAdapter.getData().get(position).getStats() != null) {
                            TemperatureTableItem temperatureTableItem = bloodPressureAdapter.getData().get(position);
                            edittText(temperatureTableItem);
                        }
                        break;
                }
            }
        });

        bloodPressureAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_val_low:
                        if (bloodPressureAdapter.getData().get(position).getStats() != null) {
                            TemperatureTableItem temperatureTableItem = bloodPressureAdapter.getData().get(position);
                            dialogdelete(temperatureTableItem);
                        }
                        break;
                }
                return true;
            }
        });
    }

    public void dialogdelete(final TemperatureTableItem temperatureTableItem) {

        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                deleteLongClick(temperatureTableItem.getId());
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.title("确认删除检测项吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder).message("检测值可以帮助医生更准确的了解你的情况");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }

    public void deleteLongClick(String itemId) {
        dailyRecordPresenter.updateAloneItemDailyRecordDetail(itemId, "", "", "", ConstantManger.DELETEDAILY, "", "");
    }


    //收缩压
    private final double BloodMinone = 50.0;
    private final double BloodMaxone = 300.0;
    //舒张压
    private final double BloodMintwo = 30.0;
    private final double BloodMaxtwo = 120.0;

    public void edittText(final TemperatureTableItem temperatureTableItem) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输血压检测值");
        View views = LayoutInflater.from(this).inflate(R.layout.dialog_edit_dlood, null, false);
        builder.setView(views);

        //收缩压
        final EditText edit_max = (EditText) views.findViewById(R.id.edit_max);
        edit_max.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
        edit_max.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString() != null && s.toString().length() > 0) {
                    TextColer(edit_max, OutliersValues.shrink(s.toString()));
                }
            }
        });
        //收缩压
        final EditText edit_min = (EditText) views.findViewById(R.id.edit_min);
        edit_min.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
        edit_min.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString() != null && s.toString().length() > 0) {
                    TextColer(edit_min, OutliersValues.Diastole(s.toString()));
                }
            }
        });

        StringBuffer stringBuffer=new StringBuffer();

        if (temperatureTableItem != null) {
            edit_max.setText(temperatureTableItem.getLogValue());
            edit_min.setText(temperatureTableItem.getPaired());
            stringBuffer.append("确定");
        }else{
            stringBuffer.append("提交");
        }

        builder.setPositiveButton(stringBuffer.toString(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String valmin = edit_min.getText().toString();
                String valmax = edit_max.getText().toString();
                int flomin = 0;
                int flomax = 0;
                if (valmin.length() == 0 || valmax.length() == 0) {
                    msg("检测值不能为空");
                    return;
                } else {
                    flomin = Integer.parseInt(valmin);
                    flomax = Integer.parseInt(valmax);
                    if (flomax < 40 || flomin < 30) {
                        msg("检测值为不可能值");
                        return;
                    }
                }

                if (BloodMinone == BloodMintwo) {
                    msg("收缩压不应低于等于舒张压");
                    return;
                }

                if (flomax > flomin) {
                    //判断收缩压是都合法
                    if (BloodMinone <= flomax && flomax <= BloodMaxone) {
                    } else {
                        msg("收缩压检测值异常");
                        return;
                    }
                    if (BloodMintwo <= flomin && flomin <= BloodMaxtwo) {
                    } else {
                        msg("舒张压检测值异常");
                        return;
                    }
                } else {
                    msg("收缩压不应低于舒张压");
                    return;
                }
                if (temperatureTableItem != null) {
                    //异常值判断
                    dailyRecordPresenter.updateAloneItemDailyRecordDetail(temperatureTableItem.getId() + "", flomax + "",
                            flomin + "", "", ConstantManger.UPDATEDAILY, abnormalVal(flomax + "", flomin + ""),
                            temperatureTableItem.getIndexId() + "");
                } else {
                    sw_blood_high.EditTextView(flomax+"");
                    sw_blood_low.EditTextView(flomin+"");
                    isUpdate=false;
                    action_preservation();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                showKeyboard(edit_max);
            }
        }, 300);

        builder.show();
    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }


    public void TextColer(EditText textView, int color) {
        if (color == 2) {
            textView.setTextColor(color(R.color.btcolor));
        } else {
            textView.setTextColor(color(R.color.red));
        }
    }

    private int color(int value) {
        return MainAppliaction.getInstance().getResources().getColor(value);
    }


    //保存
    boolean isUpdate=true;
    @OptionsItem(R.id.action_preservation)
    public void action_preservation() {

        if(isUpdate){
            if(!sw_blood_high.updateVal() && !sw_blood_low.updateVal() ){
                msg("请修改检测值");
                return;
            }
        }
        //血压高
        final String blood_high = sw_blood_high.getDetectVal();
        //血压低
        final String blood_low = sw_blood_low.getDetectVal();

        if (Float.parseFloat(blood_high) <= Float.parseFloat(blood_low)) {
            msg("收缩压不应低于舒张压");
            return;
        }
        //时分
        String timeMin = wt_time.getTime();
        //日期
        String DateTime = wd_dataAdd.getDataTime();

        final StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(DateTime);
        stringBuffer.append(" " + timeMin + ":00");

        showDialog();
        isUpdate=true;

        dailyRecordPresenter.AddDailyRecordDetailData(
                blood_high,
                stringBuffer.toString(),
                "",
                blood_low,//血压低
                ConstantManger.BLOODPRESSURENAME,
                ConstantManger.BLOODPRESSURECOMPANYNAME, abnormalVal(blood_high, blood_low));
    }


    //检测值判断
    public String abnormalVal(String blood_high, String blood_low) {
        String warn = "";
        int val = OutliersValues.Valstats(blood_high, blood_low);
        if (val == 2 || val == 3) {
            warn = "0";
        } else {
            warn = "1";
        }
        return warn;
    }

    @Override
    public void onDailyRecordDetailsSuccess(AnotherResult<DailyRecordDetailsData> data) {

        List<TemperatureTableItem> temperatureTableItemList = new ArrayList<>();
        if (data.getList().size() != 0) {
            temperatureTableItemList.add(new TemperatureTableItem(TemperatureTableItem.HEAD));
        }
        for (int i = 0; i < data.getList().size(); i++) {
            TemperatureTableItem temperatureTableItem = new TemperatureTableItem();
            temperatureTableItem.setId(data.getList().get(i).getId() + "");
            temperatureTableItem.setLogTime(data.getList().get(i).getLogTime().substring(5, 16));
            temperatureTableItem.setLogValue(data.getList().get(i).getLogValue());
            temperatureTableItem.setPaired(data.getList().get(i).getPaired());
            temperatureTableItem.setItemType(data.getList().get(i).getLogType());
            temperatureTableItem.setDailyitemDose(data.getList().get(i).getDailyitemDose());
            temperatureTableItem.setDailyitemName(data.getList().get(i).getDailyitemName());
            temperatureTableItem.setItemType(TemperatureTableItem.BODY);
            temperatureTableItem.setIndexId(data.getList().get(i).getIndexId());
            int val = OutliersValues.Valstats(data.getList().get(i).getLogValue(), data.getList().get(i).getPaired());
            temperatureTableItem.setStats(val + "");

            temperatureTableItem.setReferenceValue(ConstantManger.BLOODPRESSUREFERENCEHIGH);//参考值
            temperatureTableItemList.add(temperatureTableItem);
        }
        initAdapter(temperatureTableItemList);

        int[] index = {0, 6};
        lc_post_list.setFlashback(temperatureTableItemList, index);
        dessDialog();
    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
            ViseLog.d("血压错误信息" + msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
    }

    @Override
    public void onSubmitSuccess(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            //获取显示的日期
            msg("操作成功");
            sw_blood_high.defaultVal("120");
            sw_blood_low.defaultVal("80");
            OneDayDailyRecord();
        }
        dessDialog();
    }

    public void dessDialog() {
        if (pd != null) {
            pd.dismiss();
        }
    }


    @Override
    public void onUpdateValueSuccess(DataStateResult dataStateResult) {
        //获取显示的日期
        OneDayDailyRecord();
    }

    @Override
    public void onDeleteValueSuccess(DataStateResult dataStateResult) {
        //获取显示的日期
        OneDayDailyRecord();
    }

    //根据某时间段获取日常数据
    public void OneDayDailyRecord() {
        //获取显示的日期
        String Time = wd_dataAdd.getDataTime();
        final String type = "7";
        dailyRecordPresenter.GetUserOneDayDailyRecordData(ConstantManger.BLOODPRESSURENAME, Time, type);
    }
}
